package com.demo.multithreading;

/**
 *	线程死锁例子
 */
public class DeadLock implements Runnable {

	Object key1 = new Object();
	Object key2 = new Object();
	boolean flag = true;
	
	public static void main(String[] args) {
		DeadLock dl = new DeadLock();
		Thread t1 = new Thread(dl,"A");
		Thread t2 = new Thread(dl,"B");
		t1.start();
		t2.start();
	}
	
	public void run()
	{
		if(flag){
			flag = false;//一定要放在synchronized外面
			synchronized (key1) {
				System.out.println(Thread.currentThread().getName()+"正在执行key1"); 
				//如果不加sleep线程1可能直接执行完，就不会发生死锁
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				synchronized(key2)
				{
					System.out.println(Thread.currentThread().getName()+"正在执行key2"); 
					
				}
			}
		}else
		{
			flag = true;
			synchronized (key2) {
				System.out.println(Thread.currentThread().getName()+"正在执行key2"); 
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				synchronized(key1)
				{
					System.out.println(Thread.currentThread().getName()+"正在执行key1"); 
				}
			}
		}
		
	} 

}
